package com.example.qxfw.common.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ExcelUtil<T> {

    private Class<T> clazz;

    public ExcelUtil(Class<T> clazz) {
        this.clazz = clazz;
    }


    /**
     * 对list数据源将其里面的数据导入到excel表单
     *
     * @param response 返回数据
     * @param list 数据列表
     * @param exportFileName 生成文件名（英文）
     * @param sheetName 工作表名称
     * @throws IOException
     */
    public void exportExcel(HttpServletResponse response, List<T> list, String exportFileName, String sheetName) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = new String(exportFileName.getBytes(), "ISO8859-1");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream outputStream = response.getOutputStream();
        EasyExcel.write(outputStream, clazz).sheet(sheetName).doWrite(list);
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 用multipartFile导入Excel
     *
     * @param multipartFile 文件
     * @return
     * @throws IOException
     */
    public List<T> importExcelUseMultipartFile(MultipartFile multipartFile) throws IOException {

        InputStream inputStream = multipartFile.getInputStream();
        return importExcel(inputStream);

    }

    /**
     * 从Excel文件导入数据
     *
     * @param inputStream 输入流
     * @return 数据列表
     */
    public List<T> importExcel(InputStream inputStream) {
        List<T> dataList = new ArrayList<>();

        EasyExcel.read(inputStream, clazz, new AnalysisEventListener<T>() {
            @Override
            public void invoke(T data, AnalysisContext context) {
                dataList.add(data);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                // 所有数据解析完成后的操作
            }
        }).excelType(ExcelTypeEnum.XLSX).sheet().doRead();

        return dataList;
    }
}
